package crons

import (
	"github.com/robfig/cron/v3"

	"im/dao"
)

func Run() {
	c := cron.New()
	defer c.Start()
	c.AddFunc("* * * * *", IndexImPosts)
	c.AddFunc("* * * * *", IndexImReplys)
	c.AddFunc("* * * * *", IndexImGroups)
}

func IndexImPosts() {
	list, err := dao.NewEsJobs().List(dao.IndexNameOfPosts, 100)
	if err != nil || len(list) == 0 {
		return
	}
	var docIds = []int64{}
	for _, row := range list {
		docIds = append(docIds, row.DocId)
	}
	docList, err := dao.NewAdminPosts().GetByIds(docIds...)
	if err != nil {
		return
	}
	var ids = []int64{}
	for _, doc := range docList {
		e := dao.NewAdminPosts().IndexDoc(doc.Id, doc, false)
		if e == nil {
			ids = append(ids, doc.Id)
		}
	}
	_ = dao.NewEsJobs().Delete(dao.IndexNameOfPosts, ids...)
}
func IndexImReplys() {
	list, err := dao.NewEsJobs().List(dao.IndexNameOfReplys, 100)
	if err != nil || len(list) == 0 {
		return
	}
	var docIds = []int64{}
	for _, row := range list {
		docIds = append(docIds, row.DocId)
	}
	docList, err := dao.NewReplysAdmins().GetByIds(docIds...)
	if err != nil {
		return
	}
	var ids = []int64{}
	for _, doc := range docList {
		e := dao.NewReplysAdmins().IndexDoc(doc.Id, doc, false)
		if e == nil {
			ids = append(ids, doc.Id)
		}
	}
	_ = dao.NewEsJobs().Delete(dao.IndexNameOfReplys, ids...)
}
func IndexImGroups() {
	list, err := dao.NewEsJobs().List(dao.IndexNameOfGroups, 100)
	if err != nil || len(list) == 0 {
		return
	}
	var docIds = []int64{}
	for _, row := range list {
		docIds = append(docIds, row.DocId)
	}
	docList, err := dao.NewGroupsAdmins().GetByIds(docIds...)
	if err != nil {
		return
	}
	var ids = []int64{}
	for _, doc := range docList {
		e := dao.NewGroupsAdmins().IndexDoc(doc.Id, doc, false)
		if e == nil {
			ids = append(ids, doc.Id)
		}
	}
	_ = dao.NewEsJobs().Delete(dao.IndexNameOfGroups, ids...)
}
